package com.huifaapp.mall.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.huifaapp.mall.R;
import com.huifaapp.mall.activity.AlreadyPayActivity;
import com.huifaapp.mall.activity.AssessActivity;
import com.huifaapp.mall.activity.DetailsofPaymentActivity;
import com.huifaapp.mall.activity.GoodstoboActivity;
import com.huifaapp.mall.activity.Homefragment.WebActivity;
import com.huifaapp.mall.activity.OrderdetailsActivity;
import com.huifaapp.mall.activity.WaitPayActivity;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.base.bean.PayBean;
import com.huifaapp.mall.bean.AllorderBean;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.AlipayUtils;
import com.huifaapp.mall.view.TakePhotoPopWin;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.squareup.okhttp.Request;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Alienware on 2018/1/11.
 */

public class AllOrderListAdapter extends RecyclerView.Adapter<AllOrderListAdapter.OrderViewHolder> {
    Activity activity;
    List<AllorderBean.OrderListBean> lists;
    TakePhotoPopWin mPop;
    int position;

    public AllOrderListAdapter(Activity activity, List<AllorderBean.OrderListBean> lists) {
        this.activity = activity;
        this.lists = lists;
    }

//    public AllOrderListAdapter(FragmentActivity activity, List<GoodsReceivedBean.OrderListBean> list) {
//        this.activity = activity;
//        this.lists = list;
//    }

    @Override
    public OrderViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(activity).inflate(R.layout.item_all_orders_layout, null);
        OrderViewHolder orderViewHolder = new OrderViewHolder(activity, view);
        return orderViewHolder;
    }

    @Override
    public void onBindViewHolder(OrderViewHolder holder, int position) {
        position=position;
        holder.setData(lists.get(position));
    }

    @Override
    public int getItemCount() {
        return lists == null ? 0 : lists.size();
    }

    class OrderViewHolder extends RecyclerView.ViewHolder {
        Activity activity;
        TextView orderNumText;
        TextView orderStateText;
        TextView btbtevaluate, orderInfoText;
        View connectMjBtn, cancelBtn, pendcomm_delete, checkLogistics;
        LinearLayout shopListLayout;
        List<View> views = new ArrayList<>();
        /**
         * max size 表示最多可显示的商品数量
         */
        int MAX_SIZE = 5;
        public OrderViewHolder(Activity activity, View itemView) {
            super(itemView);
            this.activity = activity;
            orderNumText = (TextView) itemView.findViewById(R.id.orderNumText);
            orderStateText = (TextView) itemView.findViewById(R.id.orderStateText);
            btbtevaluate = (TextView) itemView.findViewById(R.id.btbtevaluate);
            connectMjBtn = itemView.findViewById(R.id.connectMjBtn);
            cancelBtn = itemView.findViewById(R.id.cancelBtn);
            pendcomm_delete = itemView.findViewById(R.id.pendcomm_delete_all);
            checkLogistics = itemView.findViewById(R.id.checkLogistics);
            orderInfoText = (TextView) itemView.findViewById(R.id.orderInfoText);
            shopListLayout = (LinearLayout) itemView.findViewById(R.id.shopListLayout);

            for (int i = 0; i < MAX_SIZE; i++) {
                View view = LayoutInflater.from(activity).inflate(R.layout.waitpay_item11, null);
                view.setVisibility(View.GONE);
                views.add(view);
                shopListLayout.addView(view);
            }
        }

        String method = "1"; //支付方式 1 微信支付，2支付宝支付。
        public void setData(final AllorderBean.OrderListBean orderListBean){
            // TODO: 2018/1/11 此处为设置数据
            orderNumText.setText("订单编号:"+orderListBean.getOrderNo()+"");
            orderInfoText.setText("共计" + orderListBean.getTotalcount() + "件商品    合计:￥"+orderListBean.getTotalprice()+" (含运费"+orderListBean.getExpressFee()+")");
            Log.e("alalalalalal",lists.get(position).getOrderNo()+"");

            //orderInfoText.setText("") 设置 共计2件商品，合计￥205(含运费￥12.0)


            /**
             * 此处为动态添加商品
             */
            int listSize = orderListBean.getData() == null ? 0 : orderListBean.getData().size();
            Log.e("listSize", listSize + "");
            for (int i = 0; i < MAX_SIZE; i++) {
                View view = views.get(i);
                if (i >= listSize) {
                    view.setVisibility(View.GONE);
                    continue;
                }
                view.setVisibility(View.VISIBLE);
                setShopItem(view, orderListBean.getData().get(i),orderListBean);
            }

            //1是待付款 3是待发货 4是待收货 5是待评论
            //此处的state我是预先随便设置的，到时候你要通过数据源的state来进行判断
            final String state = orderListBean.getState() ;
            btbtevaluate.setVisibility(View.VISIBLE);
            switch (state) {
                case 1+"":
                    orderStateText.setText("等待买家付款");
                    btbtevaluate.setText("付款");
                    connectMjBtn.setVisibility(View.VISIBLE);
                    cancelBtn.setVisibility(View.VISIBLE);
                    pendcomm_delete.setVisibility(View.GONE);
                    checkLogistics.setVisibility(View.GONE);
                    break;
                case 3+"":
                    orderStateText.setText("买家已付款");
                    btbtevaluate.setText("查看详情");
                    connectMjBtn.setVisibility(View.GONE);
                    cancelBtn.setVisibility(View.GONE);
                    pendcomm_delete.setVisibility(View.GONE);
                    checkLogistics.setVisibility(View.GONE);
                    break;
                case 4+"":
                    orderStateText.setText("卖家已发货");
                    btbtevaluate.setText("查看详情");
                    connectMjBtn.setVisibility(View.GONE);
                    cancelBtn.setVisibility(View.GONE);
                    pendcomm_delete.setVisibility(View.GONE);
                    checkLogistics.setVisibility(View.GONE);
                    break;
                case 5+"":
                    orderStateText.setText("交易成功");
                    btbtevaluate.setVisibility(View.GONE);
                    connectMjBtn.setVisibility(View.GONE);
                    cancelBtn.setVisibility(View.GONE);
                    pendcomm_delete.setVisibility(View.VISIBLE);
                    checkLogistics.setVisibility(View.VISIBLE);
                    break;
            }
            mPop=new TakePhotoPopWin(activity);
            mPop.setOnItemClickListener(new TakePhotoPopWin.OnItemClickListener() {
                @Override
                public void setOnItemClick(View v) {
                    switch (v.getId()){
                        case R.id.tv_true_pay:
                            mPop.dismiss();
                            pay(orderListBean.getOrderNo());
                            break;
                        case R.id.ll_ye_pay:
//
                            break;
                        case R.id.ll_wx_pay:
                            method="1";
                            break;
                        case R.id.ll_zfb_pay:
                            method="2";
                            break;
                        case R.id.ll_fq_pay:

                            break;
                        case R.id.ll_ye_pay_no:

                            break;
                    }
                }
            });
            mPop.setFocusable(false);
            btbtevaluate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // TODO: 2018/1/11  此处为红色按钮点击事件
                    //需要根据state来区分
                    // state == 1 代表买家点击了付款
                    // state == 3 代表买家点击了提醒发货
                    // state == 4 代表买家点击了查看详情
                    // state == 5 代表买家点击了评价
                    if (state.equals(1+"")){
                        //设置PopupWindow中的位置
                        mPop.showAtLocation(activity.findViewById(R.id.orders_main), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);


                    }else if (state.equals(3+"")){
                        Intent intent = new Intent(activity, AlreadyPayActivity.class);
                        intent.putExtra("orderNo",orderListBean.getOrderNo());
                        activity.startActivity(intent);
                    }else if (state.equals(4+"")){
                        Intent intent = new Intent(activity, GoodstoboActivity.class);
                        intent.putExtra("orderNo",orderListBean.getOrderNo());
                        activity.startActivity(intent);
                    }else if (state.equals(5+"")){
                        Intent intent = new Intent(activity,AssessActivity.class);
                        activity.startActivity(intent);
                    }
                }
            });

            connectMjBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // TODO: 2018/1/11 此处为点击  联系客服 按钮监听
                    Intent intent = new Intent(activity, WebActivity.class);
                    intent.putExtra("url","http://chat56.live800.com/live800/chatClient/chatbox.jsp?companyID=937587&configID=154412&jid=1486640810");

                    activity.startActivity(intent);

                }
            });
            cancelBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // TODO: 2018/1/11 此处为点击  取消订单 按钮监听
                    canel();
                }
            });
            pendcomm_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // TODO: 2018/1/11 此处为点击  删除订单 按钮监听
//                    Toast.makeText(activity,"进来",Toast.LENGTH_SHORT).show();
                    delete();
                }
            });
            checkLogistics.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // TODO: 2018/1/11 此处为点击  查看物流 按钮监听
                }
            });
        }

        private void pay(String orderNo){


                if ("1".equals(method)) {
                    String url = ApiManager.WXPAY_PAY+"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+AUniqueIdentifier.getDeviceId(activity)+"&orderNo="+orderNo;
//            String url = ApiManager.WXPAY_PAY+"?token=201712291124171334f3ed61d93e05404b8dc78f10c4770cf8&appId=D7B72681-8205-4C8F-8CCB-142C448203E3"
//                    +"&orderNo="+orderNo;
                    Log.e("WEB", "路径Pay=====" + url);
                    HttpUtils http = new HttpUtils();
                    http.send(HttpRequest.HttpMethod.POST, url, new RequestCallBack<String>() {
                        @Override
                        public void onLoading(long total, long current, boolean isUploading) {
//                  testTextView.setText(current + "/" + total);
                            Log.e("数据", "数据-------" + current + "/" + total);
                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
//                    textView.setText(responseInfo.result);

                            try {
                                Log.e("数据123", "数据payd-------" + responseInfo.result);
                                Gson gson = new Gson();
                                PayBean list = gson.fromJson(responseInfo.result, PayBean.class);

                                if(list.getCode().equals("10000")) {
                                    Log.e("数据123", "数据list-------" + list);
                                    IWXAPI mWxApi = WXAPIFactory.createWXAPI(activity, list.getData().getAppid(), true);
                                    mWxApi.registerApp(list.getData().getAppid());
                                    PayReq req = new PayReq();
                                    req.appId = list.getData().getAppid();
                                    req.partnerId = list.getData().getMch_id();
                                    req.prepayId = list.getData().getPrepay_id();
                                    req.nonceStr = list.getData().getNonce_str();
                                    req.timeStamp = list.getData().getTimestamp();
                                    req.packageValue ="Sign=WXPay";
                                    req.sign = list.getData().getSign();
                                    //在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                                    Log.e("数据123", "数据payd-------" + req);
                                    mWxApi.sendReq(req);
                                    Log.e("数据123", "mWxApi-------" + mWxApi);
                                }else{
                                    Toast.makeText(activity,list.getMsg(),Toast.LENGTH_SHORT).show();
                                }
                            }catch (JsonSyntaxException e){
                                Toast.makeText(activity,"未知错误",Toast.LENGTH_LONG).show();
                            }

                        }
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onFailure(HttpException error, String msg) {
                        }
                    });
                } else if ("2".equals(method)) {
                    new AlipayUtils(activity).getAlipaySignature(orderNo,SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN),AUniqueIdentifier.getDeviceId(activity));
                } else {
                    ToastUtils.showShortSafe("获取信息失败!");
                }
            }
        }
        public void setShopItem(View view, AllorderBean.OrderListBean.DataBean dataBean, final AllorderBean.OrderListBean orderListBean){
            Log.e("setShopItem", dataBean.toString());
            ImageView pendpay_im;
            TextView pendpay_shopname, pendpay_xj, pendpay_yj, pendpay_num, tv_color, tv_size;
            pendpay_im = (ImageView) view.findViewById(R.id.pendpay_im);
            pendpay_shopname = (TextView) view.findViewById(R.id.pendpay_shopname);
            pendpay_xj = (TextView) view.findViewById(R.id.pendpay_xj);
            pendpay_yj = (TextView) view.findViewById(R.id.pendpay_yj);
            pendpay_num = (TextView) view.findViewById(R.id.pendpay_num);
            tv_color = (TextView) view.findViewById(R.id.tv_color);
            tv_size = (TextView) view.findViewById(R.id.tv_size);

            Glide.with(activity).load(dataBean.getGoodsImg()).into(pendpay_im);   //加载商品图片

            pendpay_shopname.setText(dataBean.getGoodsName());   //商品的名字
            pendpay_xj.setText("¥" + dataBean.getPrice());   //商品的现价
            pendpay_yj.setText("¥" + dataBean.getOrginPrice());   //商品的原价
            pendpay_yj.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);   //给商品原价的TextView添加删除线
            pendpay_num.setText("x" + dataBean.getCount());   //商品的个数


            AllorderBean.OrderListBean.DataBean.ParamBean param = dataBean.getParam();
            String color = param.get颜色() == null ? "无" : param.get颜色();   //三元运算符   判断param.getColor()是否为null  如果是null则取 : 前面的值，否则后面的值
            String brand = param.get尺寸() == null ? "**" : param.get尺寸();   //同上
            tv_color.setText("颜色分类:" + color + "；");   //商品的颜色
            tv_size.setText("尺寸:" + brand);   //商品的尺寸
            final String state = orderListBean.getState() ;
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // TODO: 2018/1/11 此处为点击 商品 监听  如需进去商品详情 就在这个监听里面
                    if (state.equals(1+"")){
                        Intent intent = new Intent(activity, WaitPayActivity.class);
                        intent.putExtra("orderNo",orderListBean.getOrderNo());
                        activity.startActivity(intent);
                    }else if (state.equals(3+"")){
                        Intent intent = new Intent(activity, AlreadyPayActivity.class);
                        intent.putExtra("orderNo",orderListBean.getOrderNo());
                        activity.startActivity(intent);
                    }
                    else if (state.equals(4+"")){
                        Intent intent = new Intent(activity, GoodstoboActivity.class);
                        intent.putExtra("orderNo",orderListBean.getOrderNo());
                        activity.startActivity(intent);
                    }else if (state.equals(5+"")){
                        Intent intent = new Intent(activity, OrderdetailsActivity.class);
                        intent.putExtra("orderNo",orderListBean.getOrderNo());
                        activity.startActivity(intent);
                    }
                }
            });
        }



    private void canel() {
        AlertDialog alertDialog = new AlertDialog.Builder(activity).setTitle("提示").setMessage("是否需要取消？")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        final String order = lists.get(position).getOrderNo();
                        Log.e("",ApiManager.BASE_NIUPAI_URL+"orders/cancelorders"+"?token="+SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)
                                +"&appId="+AUniqueIdentifier.getDeviceId(activity)+"&orderNo="+order);
                        OkHttpUtils.post().url(ApiManager.BASE_NIUPAI_URL+"orders/cancelorders")
                                .addParams("token",SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                                .addParams("appId",AUniqueIdentifier.getDeviceId(activity))
                                .addParams("orderNo",order)
                                .build()
                                .execute(new StringCallback() {
                                    @Override
                                    public void onError(Request request, Exception e) {
                                        ToastUtils.showShort("取消失败");
                                    }

                                    @Override
                                    public void onResponse(String response) {
                                        Log.e("HB",response);
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            String code =  jsonObject.getString("code");
                                            if (code.equals("10000"))
                                            {
                                                ToastUtils.showShort("删除成功");
                                                lists.remove(position);
                                                notifyDataSetChanged();
                                            }else if(code.equals("10015")){
                                                ToastUtils.showShort(jsonObject.getString("msg"));
                                                ToastUtils.showShort("删除失败");
                                            }else {
                                                ToastUtils.showShort(jsonObject.getString("msg"));
                                                ToastUtils.showShort("删除失败");
                                            }

                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });

                    }
                }).create();
        alertDialog.show();

    }

    private void delete() {
        AlertDialog alertDialog = new AlertDialog.Builder(activity).setTitle("提示").setMessage("是否需要删除？")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        final String id = lists.get(position).getOrderNo();
                        Log.e("",ApiManager.BASE_NIUPAI_URL+"orders/delorders"+"?token="+SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)
                                +"&appId="+AUniqueIdentifier.getDeviceId(activity)+"&orderNo="+id);
                        OkHttpUtils.post().url(ApiManager.BASE_NIUPAI_URL+"orders/delorders")
                                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                                .addParams("appId", AUniqueIdentifier.getDeviceId(activity))
                                .addParams("orderNo",id)
                                .build()
                                .execute(new StringCallback() {

                                    @Override
                                    public void onError(Request request, Exception e) {
                                        ToastUtils.showShort("删除失败");
                                    }

                                    @Override
                                    public void onResponse(String response) {
                                        Log.e("HB",response);
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            String code =  jsonObject.getString("code");
                                            if (code.equals("10000"))
                                            {
                                                lists.remove(position);
                                                notifyDataSetChanged();
                                            }else if(code.equals("10015")){
                                                ToastUtils.showShort(jsonObject.getString("msg"));
//                                                ToastUtils.showShort("删除失败");
                                            }else {
                                                ToastUtils.showShort(jsonObject.getString("msg"));
//                                                ToastUtils.showShort("删除失败");
                                            }

                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                     }
                                }
                          });
                    }
                }).create();
        alertDialog.show();

    }
}
